package com.example.pm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.pm.common.basic.expect.expectToExcel;
import com.example.pm.common.result.R;
import com.example.pm.domain.Car;
import com.example.pm.domain.Employee;
import com.example.pm.mapper.CarMapper;
import com.example.pm.mapper.EmployeeMapper;
import com.example.pm.service.ExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ExportServiceImpl implements ExportService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private CarMapper carMapper;

    @Override
    public R<Map<String, Object>> exportEmployees(List<Integer> ids) {
        //获取导出的员工列表
        List<Employee> employees = employeeMapper.selectList(new LambdaQueryWrapper<>());
        if (!ids.isEmpty()) {
            employees = employees.stream().filter(o -> ids.contains(o.getId())).collect(Collectors.toList());
        }
        Map<String, Object> map = getExpectMap(Employee.class);
        map.put("fileName", "员工信息表");
        map.put("list", employees);
        return R.ok("导出成功", map);
    }

    @Override
    public R<Map<String, Object>> exportCars() {
        Map<String, Object> map = getExpectMap(Car.class);
        map.put("fileName", "车辆信息表");
        map.put("list", carMapper.selectList(new LambdaQueryWrapper<>()));
        return R.ok("导出成功", map);
    }


    public Map<String, Object> getExpectMap(Class<?> c) {
        Field[] fields = c.getDeclaredFields();
        List<String> headers = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (Field field : fields) {
            if (field.getAnnotation(expectToExcel.class).expect()) {
                String header = field.getAnnotation(expectToExcel.class).header();
                headers.add(header);
                String name = field.getName();
                names.add(name);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("headers", headers);
        map.put("names", names);
        return map;
    }
}
